/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.me.counttimer;

import android.app.Activity;
import android.content.Intent ;
import android.widget.ListView;
import android.widget.ListAdapter ;
import android.widget.ArrayAdapter ;
import android.os.Bundle;
import android.app.TimePickerDialog;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.AdapterView.*;
import android.widget.AdapterView;
import android.app.AlertDialog ;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Vector ;
import android.os.CountDownTimer ;
import android.util.Log;

import com.android.MyDatabase ;
import java.util.concurrent.TimeUnit;

import java.lang.Object;
import android.speech.tts.TextToSpeech ;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.admob.android.ads.AdManager;
import com.admob.android.ads.AdView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.me.counttimer.CircleTimer;

/**
 *
 * @author ksemuldie
 */
public class PlayerSessionActivity extends Activity implements TextToSpeech.OnInitListener  {
  private static final int STATE_PLAYER_PAUSE = 0 ;
  private static final int STATE_PLAYER_RUNNING = 1 ;

  private int id_session = 0 ;
  private static List<ObjRepeat> ArrayRepeat ;
  private MyDatabase db;

  private ProgressBar ProgressRepeat ;
  private ProgressBar ProgressGlobal ;
  private TextView ProgressText ;
  private CircleTimer CircleTimer ;
  private TextView SessionName ;
  private LinearLayout RootLayout ;

  private int repeat_for ;
  private int position ;
  private static long msecond_left ;

  private CountDownTimer MyCountDown ;
  private int CountDownState = this.STATE_PLAYER_PAUSE  ;

  private TextToSpeech myTTS;

  @Override
  protected void onResume(){
    super.onResume();
  }

  @Override
  public void onDestroy() {
    db.close();

    if (myTTS != null) {
      myTTS.stop();
      myTTS.shutdown();
    }

    if(MyCountDown != null){
      MyCountDown.cancel();
      MyCountDown = null ;
    }

    super.onDestroy();
  }

  @Override
  protected void onStop(){
    super.onStop();

    
  }

  public void onInit(int status) {
    // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
    if (status == TextToSpeech.SUCCESS) {
        // Set preferred language to US english.
        // Note that a language may not be available, and the result will indicate this.
        int result = myTTS.setLanguage(Locale.getDefault());
        // Try this someday for some interesting results.
        // int result mTts.setLanguage(Locale.FRANCE);
        if (result == TextToSpeech.LANG_MISSING_DATA ||
            result == TextToSpeech.LANG_NOT_SUPPORTED) {
           // Lanuage data is missing or the language is not supported.
            Log.e("TTS", "Language is not available.");
            Toast.makeText(getBaseContext(),"Language is not available.",Toast.LENGTH_SHORT).show();
        } else {
            // Check the documentation for other possible result codes.
            // For example, the language may be available for the locale,
            // but not for the specified country and variant.

            // The TTS engine has been successfully initialized.
            // Allow the user to press the button for the app to speak again.
            //mAgainButton.setEnabled(true);
            // Greet the user.
            //speechText("");
        }
    } else {
        // Initialization failed.
        //Log.e("TTS", "Could not initialize TextToSpeech.");
        Toast.makeText(getBaseContext(),"Could not initialize TextToSpeech.",Toast.LENGTH_SHORT).show();
    }
  }

  private ArrayList<ObjRepeat> loadRepeat(){
    ArrayList<ObjRepeat> arrayReturn = new ArrayList<ObjRepeat>() ;

    Cursor CRepeat = db.fetchRepeat(this.id_session) ;

    for(CRepeat.moveToFirst();!CRepeat.isAfterLast() ; CRepeat.moveToNext() ){
      Log.i("INFOC" , Integer.toString(CRepeat.getInt(3)) );
      ObjRepeat obj = new ObjRepeat() ;

      obj.color = CRepeat.getInt(4) ;
      obj.second = CRepeat.getInt(3) ;
      obj.name = CRepeat.getString(2) ;

      arrayReturn.add(obj) ;
    }

    return arrayReturn ;
  }

  private void speechText(String StringToSpeech) {
    // Select a random hello.
    myTTS.speak(StringToSpeech,
        TextToSpeech.QUEUE_FLUSH,  // Drop all pending entries in the playback queue.
        null);
  }

  private void getViewElement(){
    ProgressRepeat = (ProgressBar) findViewById(R.id.repeat_progress) ;
    ProgressGlobal = (ProgressBar) findViewById(R.id.global_progress) ;
    ProgressText = (TextView)findViewById(R.id.progress_text);
    CircleTimer = (CircleTimer) findViewById(R.id.circle_timer) ;
    SessionName = (TextView) findViewById(R.id.label_repeat);
    RootLayout = (LinearLayout)findViewById(R.id.root_layout);
  }

  /** Called when the activity is first created. */
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    myTTS = new TextToSpeech(this , this);

    super.onCreate(savedInstanceState);

    boolean resume = !(savedInstanceState == null) ;

    Bundle extras = getIntent().getExtras();
    id_session = extras.getInt(MainActivity.VAL_ID_SESSION) ;

    AdManager.setTestDevices( new String[]
    { AdManager.TEST_EMULATOR } );

    setContentView(R.layout.player_session);

    db=new MyDatabase(getApplicationContext());
    db.open();//open db

    Cursor CSession = db.fetchSession(id_session) ;
    startManagingCursor(CSession);
    //First row exist
    if(CSession.moveToFirst()) {
      int total_second = db.fetchTimeSession(id_session)*CSession.getInt(2) ;

      this.getViewElement();

      ProgressGlobal.setMax(total_second*1000);

      if(resume){
        this.repeat_for = savedInstanceState.getInt("repeat_for");
        this.position = savedInstanceState.getInt("position");
        this.msecond_left = savedInstanceState.getLong("msecond_left");
        ProgressGlobal.setProgress(savedInstanceState.getInt("ProgressGlobal"));

        for(int i = 0; i < ArrayRepeat.size() ; i++){
          ObjRepeat Obj = ArrayRepeat.get(i);
          CircleTimer.addArc(Obj.second*1000,Obj.color);
        }

        this.playRepeat(this.repeat_for, this.position, this.msecond_left);
      }else {
        this.ArrayRepeat = new ArrayList<ObjRepeat>() ;
        this.ArrayRepeat = this.loadRepeat() ;

        for(int i = 0; i < ArrayRepeat.size() ; i++){
          ObjRepeat Obj = ArrayRepeat.get(i);
          CircleTimer.addArc(Obj.second*1000,Obj.color);
        }

        this.playRepeat(CSession.getInt(2) );
      }
      
    }

    
  }

  private void playRepeat(final int repeat_for){
    this.playRepeat(repeat_for, 0 , 0);
  }

  private void playRepeat(final int repeat_for ,final int position){
    this.playRepeat(repeat_for, position , 0);
  }

  private void playRepeat(final int repeat_for ,final int position , long msecond_left){
    this.repeat_for = repeat_for ;
    this.position = position ;
    this.msecond_left = msecond_left ;

    //Check if position more than size array
    if(position >= ArrayRepeat.size()){
      //Check end repeat_for
      if(repeat_for - 1 > 0){
        playRepeat(repeat_for-1 , 0) ;
      } else {
        this.finish();
      }
      return ;
    }

    ObjRepeat ObjRepeat = ArrayRepeat.get(position) ;
    final int end_second = ObjRepeat.second ;
    final int end_msecond = (end_second)*1000 ;

    ProgressRepeat.setMax(end_msecond) ;

    if( msecond_left == 0){
      ProgressRepeat.setProgress(0) ;
    }else {
      ProgressRepeat.setProgress(end_msecond - (int)msecond_left) ;
      Log.i("INFOPROGRESSREPEAT "+end_msecond+" - "+(int)msecond_left+" = ",Integer.toString(end_msecond - (int)msecond_left));
    }
    
    

    SessionName.setText(ObjRepeat.name);
    RootLayout.setBackgroundColor(ObjRepeat.color);
    ProgressText.setText("("+repeat_for+")-"+Long.toString((end_msecond - (end_msecond - msecond_left)) / 1000)+"/"+(end_second));

    final int globalNowProgress = ProgressGlobal.getProgress() ;

    if(this.msecond_left == 0){
      this.msecond_left = end_msecond ;
      speechText(ObjRepeat.name);
    }
    final long msecond_to_end = this.msecond_left ;

    AdView ad = (AdView)findViewById(R.id.ad);
    ad.requestFreshAd();

    MyCountDown = new CountDownTimer(msecond_to_end, 50) {
      public void onTick(long millisUntilFinished) {
        PlayerSessionActivity.msecond_left = millisUntilFinished ;

        ProgressRepeat.setProgress((int)(end_msecond - millisUntilFinished));

        ProgressText.setText("("+repeat_for+")-"+
                ((int)((end_msecond - millisUntilFinished)/1000))+
                "/"+
                ((int)(end_msecond/1000))
                ) ;

        ProgressGlobal.setProgress((int)(globalNowProgress + (msecond_to_end - millisUntilFinished)));


        Log.i("INFOV" , Long.toString(PlayerSessionActivity.msecond_left));

        CircleTimer.setHand(ProgressGlobal.getProgress());
      }

      public void onFinish() {
        playRepeat(repeat_for , position+1) ;
      }
    }.start();
    CountDownState = this.STATE_PLAYER_RUNNING ;
  }

  // MENU SESSION
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.player_menu, menu);

      return true;
  }

  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {

      if(this.CountDownState == 1) {
          MenuItem item = menu.getItem(0) ;
          item.setVisible(true);
      } else {
          MenuItem item = menu.getItem(1) ;
          item.setVisible(true);
      }

      return super.onPrepareOptionsMenu(menu);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
      case R.id.pause:
        MyCountDown.cancel();
        CountDownState = this.STATE_PLAYER_PAUSE ;
        item.setVisible(false) ;
        Log.i("INFOV" , "Pause "+Long.toString(this.msecond_left));

        return true;
      case R.id.play:
        Log.i("INFO" , "PLAY COUNTER");
        CountDownState = this.STATE_PLAYER_RUNNING ;
        item.setVisible(false) ;
        Log.i("INFOV" , "Play "+Long.toString(this.msecond_left));
        playRepeat(this.repeat_for , this.position , this.msecond_left);
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  // END MENU SESSION

  // PAUSE AND PLAY
  protected void onSaveInstanceState(Bundle player) {
    player.putInt("repeat_for", this.repeat_for);
    player.putInt("position", this.position);
    player.putLong("msecond_left", this.msecond_left);
    player.putInt("ProgressGlobal", ProgressGlobal.getProgress());

    MyCountDown.cancel() ;

    super.onSaveInstanceState(player);
  }
  // END PAUSE AND PLAY

  private class ObjRepeat {
    public String name = "" ;
    public int second = 0 ;
    public int color = 0 ;
  }
}